package com.mt.api.modules.service.impl;

import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.collect.Lists;
import com.mt.api.constants.constant.Constants;
import com.mt.api.constants.enums.CustomerStatusEnum;
import com.mt.api.modules.domain.AppCustomer;
import com.mt.api.modules.domain.AppOrder;
import com.mt.api.modules.domain.bo.CustomerAddBo;
import com.mt.api.modules.domain.bo.CustomerDelBo;
import com.mt.api.modules.domain.dto.CustomerBillStatDto;
import com.mt.api.modules.domain.vo.CustomerInfoVo;
import com.mt.api.modules.domain.vo.CustomerWithAmountVo;
import com.mt.api.modules.manager.ICustomerBillManager;
import com.mt.api.modules.manager.ICustomerManager;
import com.mt.api.modules.manager.IOrderManager;
import com.mt.api.modules.mapstruct.CustomerMapStruct;
import com.mt.api.util.AmountUtil;
import com.mt.common.response.WebResponse;
import com.mt.common.response.WebResponseUtils;
import com.mt.api.modules.domain.bo.CustomerListBo;
import com.mt.api.modules.domain.bo.CustomerPageBo;
import com.mt.api.modules.domain.vo.AppCustomerVo;
import com.mt.api.modules.mapper.AppCustomerMapper;
import com.mt.api.modules.service.AppCustomerService;
import lombok.RequiredArgsConstructor;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @author plover
 * @description 服务实现
 * @date 2020-07-06
 **/
@Service
@RequiredArgsConstructor
public class AppCustomerServiceImpl extends ServiceImpl<AppCustomerMapper, AppCustomer> implements AppCustomerService {

    private final ICustomerManager customerManager;
    private final ICustomerBillManager customerBillManager;
    private final IOrderManager orderManager;

    private final CustomerMapStruct customerMapStruct;

    @Override
    public WebResponse addCustomer(CustomerAddBo bo) {
        AppCustomer customer = customerMapStruct.boToEntity(bo);

        CustomerListBo customerListBo = new CustomerListBo();
        customerListBo.setReceiver(bo.getReceiver());
        customerListBo.setRphone(bo.getRphone());
        List<AppCustomer> customerList = customerManager.getListByParam(customerListBo);
        if (CollectionUtils.isEmpty(customerList)) {
            customer.setStatus(Constants.CustomerState.NORMAL);
            customerManager.save(customer);
        } else {
            return WebResponseUtils.error("该客户已存在");
        }
        return WebResponseUtils.success(customer.getId());
    }

    @Override
    public WebResponse editCustomer(CustomerAddBo bo) {
        AppCustomer customer = customerMapStruct.boToEntity(bo);
        customerManager.updateById(customer);
        return WebResponseUtils.success();
    }

    @Override
    public WebResponse delCustomer(CustomerDelBo bo) {
        customerManager.removeById(bo.getId());
        return WebResponseUtils.success();
    }

    @Override
    public WebResponse<CustomerInfoVo> getCustomerInfo(Integer id) {
        AppCustomer customer = customerManager.getById(id);
        if (Objects.isNull(customer)) {
            return WebResponseUtils.errorParam("客户不存在");
        }
        CustomerInfoVo vo = customerMapStruct.toVo(customer);

        List<CustomerBillStatDto> statDtoList = customerBillManager.getCustomerBillStat(id);
        if (CollectionUtils.isNotEmpty(statDtoList)) {
            CustomerBillStatDto statDto = statDtoList.get(0);
            vo.setUnSettleAmount(AmountUtil.divideHundred(statDto.getUnSettleAmount()));
        }

        AppOrder order = orderManager.getLastOrderByCustomerId(id);
        if (Objects.nonNull(order)) {
            vo.setLastOrderTime(DateUtil.formatDate(order.getOrderTime()));
            long between = DateUtil.between(order.getOrderTime(), new Date(), DateUnit.DAY);
            vo.setLastOrderDays(between);
        }
        return WebResponseUtils.success(vo);
    }

    @Override
    public WebResponse listByBrandId(CustomerListBo customerListBo) {
        LambdaQueryWrapper<AppCustomer> wrapper = Wrappers.<AppCustomer>lambdaQuery()
                .eq(AppCustomer::getStatus, CustomerStatusEnum.NORMAL.getCode())
                .nested(StringUtils.isNotEmpty(customerListBo.getSearchVal()), appCustomerLambdaQueryWrapper -> appCustomerLambdaQueryWrapper.like(AppCustomer::getReceiver, customerListBo.getSearchVal())
                        .or().like(AppCustomer::getRphone, customerListBo.getSearchVal()).or().like(AppCustomer::getRarea, customerListBo.getSearchVal()))
                .orderByDesc(AppCustomer::getWeight);
        if (StringUtils.isEmpty(customerListBo.getSearchVal())) {
            wrapper.last("limit 15");
        }
        List<AppCustomer> customers = baseMapper.selectList(wrapper);
        List<AppCustomerVo> appCustomerVos = Lists.newArrayList();
        customers.forEach(customer -> {
            AppCustomerVo appCustomerVo = new AppCustomerVo();
            BeanUtils.copyProperties(customer, appCustomerVo);
            appCustomerVos.add(appCustomerVo);
        });
        return WebResponseUtils.successList(appCustomerVos);
    }

    @Override
    public WebResponse pageByBrandId(CustomerPageBo customerPageBo) {
        Page pageList = customerManager.getPageList(customerPageBo);
        List<AppCustomer> records = pageList.getRecords();
        List<AppCustomerVo> appCustomerVos = records.stream().map(customer -> {
            AppCustomerVo appCustomerVo = new AppCustomerVo();
            BeanUtils.copyProperties(customer, appCustomerVo);
            return appCustomerVo;
        }).collect(Collectors.toList());
        pageList.setRecords(appCustomerVos);
        return WebResponseUtils.successPage(pageList);
    }

    @Override
    public WebResponse getCustomerStatPage(CustomerPageBo customerPageBo) {
        Page<CustomerWithAmountVo> page = customerManager.getCustomerStatPage(customerPageBo);
        return WebResponseUtils.successPage(page);
    }
}